package com.baizhi.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Aspect
//@Component
public class CategoryAOP {

    private static final Logger log = LoggerFactory.getLogger(CategoryAOP.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(com.baizhi.Annotation.CategoryAnno)")
    public Object around(ProceedingJoinPoint joinPoint) {
        log.info("进入环绕切面");

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //获取类的全限定类名[大的redis键]
        String nameKey = joinPoint.getClass().getName();

        StringBuilder sb = new StringBuilder();
        sb.append(nameKey);

        sb.append("&");
        //获取参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            sb.append(arg);
        }
        String s = sb.toString();

        HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
        Boolean aBoolean = hash.hasKey(nameKey, s);
        Object proceed = null;
        if (aBoolean) {
            //获取对应的值
            proceed = hash.get(nameKey, s);
        } else {
            //放行
            try {
                proceed = joinPoint.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            hash.put(nameKey, s, proceed);

        }
        return proceed;


    }
}
